<!--
/**
* @name OperateForm
* @description ** 新增编辑用户
* @author mdong
* @date 2020-05-12
* @param {**} ** **
* @example ***
*/
-->
<template>
  <div calss="operate-form">
    <a-modal :title="title"
             :maskClosable="false"
             :width="800"
             :wrapClassName="isDetails?'modal-box modal-hidden-footer':'modal-box'"
             :visible="operateVisible"
             :confirm-loading="confirmLoading"
             @ok="handleSubmit"
             okText="提交"
             :okButtonProps="{props:{icon:'save'}}"
             :cancelButtonProps="{props:{icon:'close-circle'}}"
             @cancel="handleVisible"
             :destroyOnClose="true">
      <form-loading :formLoadingVisible="formLoadingVisible"></form-loading>
      <!-- <h3 class="form-title"> 新增组织 </h3> -->
      <a-form-model ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    :hideRequiredMark="isDetails"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="设备名称"
                               prop="equipmentName">
              <a-input allowClear
                       v-show="!isDetails"
                       placeholder="请输入设备名称"
                       v-model.trim="form.equipmentName"
                       :maxLength="20"></a-input>
              <span v-show="isDetails">{{form.equipmentName}}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="设备ID"
                               prop="equipmentId">
              <a-input allowClear
                       v-show="!isDetails"
                       v-model.trim="form.equipmentId"
                       placeholder="请输入设备ID"
                       :maxLength="20"></a-input>
              <span v-show="isDetails" style="white-space: nowrap;">{{form.equipmentId}}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="设备状态"
                               prop="equipmentType">
              <a-select v-model="form.equipmentType"
                        v-show="!isDetails"
                        style="width: 100%">
                <a-select-option v-for="{id, name, value} in equipmentTypes"
                                 :key="value"
                                 :vaule="value">{{name}}</a-select-option>
              </a-select>
              <span v-show="isDetails">{{convertConstName(equipmentTypes, form.equipmentType)}}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="污染类型"
                               prop="polluteType">
              <a-select v-model="form.polluteType"
                        v-show="!isDetails"
                        style="width: 100%">
                <a-select-option v-for="(item, index) in polluteTypeConst"
                                 :key="index"
                                 :value="item.value">{{ item.name }}</a-select-option>
              </a-select>
              <span v-show="isDetails">{{convertConstName(polluteTypeConst, form.polluteType)}}</span>
            </a-form-model-item>
            <!-- <a-form-model-item label="企业名称" prop="entinfoId">
              <a-select
                v-model="form.entinfoId"
                :disabled="optType === 'view'"
                style="width: 100%"
                @change="changeEntinfoId"
                allowClear
              >
                <a-select-option
                  v-for="(item,index) in entinfoIdConst "
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-model-item>-->
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="生产线"
                               prop="workshopId">
              <a-select v-model="form.workshopId"
                        placeholder="请选择生产线"
                        v-show="!isDetails"
                        :disabled="optType === 'add'"
                        style="width: 100%"
                        allowClear>
                <a-select-option v-for="(item, index) in workshopIdConst"
                                 :key="index"
                                 :value="item.id">{{ item.productionLineName }}</a-select-option>
              </a-select>
              <span v-show="isDetails" style="white-space: nowrap;">{{convertConstName(workshopIdConst, form.workshopId, 'productionLineName', 'id')}}</span>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item label="标准负荷值"
                               prop="threshold">
              <a-input allowClear
                       :disabled="optType === 'view'"
                       v-model="form.threshold"
                       :maxLength="20"></a-input>
            </a-form-model-item>
          </a-col> -->
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { getDictData } from '@/request/api/common'
import {
  // queryHnEntinfoList,
  queryHnWorkshopList
} from '@/request/api/enterpriseInformationManagement/enterpriseInformation'
import { validators } from '@/utils/validate'
import { getHnEquipmentById, checkEquipmentId } from '@/request/api/enterpriseInformationManagement/equipmentManagement'
import { FormModel, Modal, Row, Col, Input, Select } from 'ant-design-vue'
import FormLoading from '@/components/FormLoading'
import { convertConstName } from '@/utils/filter'
export default {
  name: 'OperateForm',
  components: {
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AModal: Modal,
    FormLoading,
    ARow: Row,
    ACol: Col,
    AInput: Input,
    ASelect: Select,
    ASelectOption: Select.Option
  },
  props: {
    // 是否打开新增和编辑抽屉
    operateVisible: {
      type: Boolean,
      required: true
    },
    optType: {
      type: String,
      default: 'add'
    },
    // 提交按钮loading
    confirmLoading: {
      type: Boolean,
      required: true
    },
    // 新增和编辑抽屉数据
    operateData: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      form: {
        equipmentType: '1'
      },
      polluteTypeConst: [],
      rules: {
        equipmentName: [
          { required: true, message: '请输入设备名称', trigger: 'change' },
          {
            validator: validators.validatorEmoji,
            message: '请输入合法的字符',
            trigger: 'change'
          }
        ],
        // entinfoId: [
        //   { required: false, message: '请选择企业', trigger: 'change' }
        // ],
        polluteType: [
          { required: true, message: '请选择污染类型', trigger: 'change' }
        ],
        equipmentId: [
          { required: true, message: '请输入设备ID', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              console.log('触发checkEquipmentId...')
              checkEquipmentId({
                equipmentId: this.form.equipmentId,
                id: this.form.id || ''
              }).then((res) => {
                if (res.code === '0') {
                  callback()
                } else {
                  callback(new Error(res.msg))
                }
              }).catch(() => {
                callback(new Error('检查设备id失败'))
              })
            },
            trigger: 'none'
          }
        ],
        workshopId: [
          { required: false, message: '请选择生产线/车间', trigger: 'change' }
        ],
        equipmentType: [
          {
            required: true,
            message: '请选择设备状态',
            trigger: 'change'
          }
        ]
      },
      // 标题
      title: '',
      // 表单加载loading
      formLoadingVisible: false,
      entinfoIdConst: [],
      workshopIdConst: [],
      // 停用 启用 字典
      equipmentTypes: []
    }
  },
  watch: {
    // 监听抽屉打开关闭
    operateVisible: {
      async handler (newV, oldV) {
        // 打开抽屉
        if (newV) {
          // 新增
          this.formLoadingVisible = true
          if (this.optType === 'add') {
            this.title = '新增设备'
            // this.form.parentName = this.operateData.parentName;
            // for (const key in this.operateData) {
            //   if (key !== "parentName") {
            //     this.operateData[key] = "";
            //   }
            // }
            this.form = Object.assign({}, this.operateData)
            await Promise.all([this.getDictDataList(), this.queryHnWorkshopList(this.form.entinfoId)])
          }
          // 编辑
          if (this.optType === 'edit') {
            this.title = '编辑设备'
            this.form = Object.assign({}, this.operateData)
            await Promise.all([this.getDictDataList(), this.getHnEquipmentInfoAndWorkshopList()])
          } else if (this.optType === 'view') {
            this.title = '设备详细'
            this.form = Object.assign({}, this.operateData)
            await Promise.all([this.getDictDataList(), this.getHnEquipmentInfoAndWorkshopList()])
          }
          this.formLoadingVisible = false
        } else {
          this.$refs.ruleForm.resetFields()
          for (const key in this.form) {
            this.form[key] = ''
          }
        }
      }
    }
  },
  computed: {
    isDetails () {
      return this.optType === 'view'
    }
  },
  beforeDestroy () {
    this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
    for (const key in this.operateData) {
      this.operateData[key] = ''
    }
  },
  created () {
    this.getDictDataList()
  },
  methods: {
    convertConstName,
    // 获取数据字典
    async getDictDataList () {
      const params = 'Y-0B-008,Y-002'
      // const entinfoIdConst = await queryHnEntinfoList({})
      // if (entinfoIdConst.code === '0') {
      //   this.entinfoIdConst = entinfoIdConst.data
      // }
      getDictData(params).then(res => {
        if (res.code === '0') {
          const data = res.data
          this.polluteTypeConst = data['Y-0B-008']
          this.equipmentTypes = data['Y-002']
        }
      })
    },
    // 通过企业id得到生产线
    async queryHnWorkshopList (entinfoId) {
      await queryHnWorkshopList({ entinfoId }).then(res => {
        if (res.code === '0') {
          this.workshopIdConst = res.data
        }
      })
    },
    // 通过设备id 得到编辑框信息
    async getHnEquipmentInfoAndWorkshopList () {
      return await getHnEquipmentById({
        id: this.form.id // 设备id
      }).then(async res => {
        this.form = Object.assign({}, res.data)
        if (res.code === '0') {
          return await this.queryHnWorkshopList(res.data.entinfoId)
        }
      })
    },
    handleSubmit () {
      this.$emit('update:confirmLoading', true) // 检查设备id
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          this.$emit('handleSubmit', this.form)
        } else {
          this.$emit('update:confirmLoading', false)
          this.$message.error('请完善信息！')
          return false
        }
      })
    },
    // 关闭抽屉
    handleVisible () {
      this.$emit('handleVisible', false)
    }
  }
}
</script>
<style lang="scss">
.form-title {
  font-size: 16px;
  border-bottom: 1px solid #e8e8e8;
  height: 40px;
  margin-bottom: 20px;
}
</style>
